package com.example.dorm1_demo.service;

import com.example.dorm1_demo.entity.User;
import com.example.dorm1_demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.regex.Pattern;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    // 密码强度正则：至少8位，包含字母和数字
    private static final String PASSWORD_PATTERN = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d@$!%*#?&]{8,}$";

    // 用户注册功能
    // 验证密码强度，检查用户名、邮箱、手机号的唯一性，并插入用户数据
    public boolean register(User user) {
        if (!isValidPassword(user.getPassword())) {
            return false;
        }
        // 检查用户名、邮箱、手机号是否已存在
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            return false;
        }
        if (StringUtils.hasText(user.getEmail()) && userMapper.selectByEmail(user.getEmail()) != null) {
            return false;
        }
        if (StringUtils.hasText(user.getPhone()) && userMapper.selectByPhone(user.getPhone()) != null) {
            return false;
        }
        user.setRole("user"); // 默认用户角色
        return userMapper.insert(user) > 0;
    }

    // 用户登录功能
    public User login(String account, String password) {
        User user = userMapper.selectByUsername(account);
        if (user == null && account.contains("@")) {
            user = userMapper.selectByEmail(account);
        }
        if (user == null && account.matches("\\d+")) {
            user = userMapper.selectByPhone(account);
        }

        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    // 修改用户密码
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        if (!isValidPassword(newPassword)) {
            return false;
        }

        User user = userMapper.selectByUsername(username);
        if (user != null && user.getPassword().equals(oldPassword)) {
            return userMapper.updatePassword(username, newPassword) > 0;
        }
        return false;
    }

    //
    private boolean isValidPassword(String password) {
        return password != null && Pattern.matches(PASSWORD_PATTERN, password);
    }
}